<script setup lang="ts">
defineOptions({
  name: "pmTable"
});

import { ref, computed, inject, markRaw } from "vue";
import { useRouter } from "vue-router";
import { View, Modeling } from "@px-ui/icons-vue";
import {
  SizeType,
  ChartTypeType,
  HeightKey,
  ChartTypeKey,
  ChartListType,
  ChartListKey,
  LockType,
  FactoryLockTypeKey,
  WorkbenchLockTypeKey
} from "../utils";
import { getFabPMDetail, getFactoryPMDetail } from "@/api/modules/fab";
import commonTable from "@/views/common/components/commonTable/index.vue";
import pmPlanDetail from "./pmPlanDetail.vue";
import { useTableCloumns, useTableCloumns2, useGunterTableData } from "../hooks";
import { useRouterStoreHook } from "@/store/modules/router";
import dayjs from "dayjs";
import weekday from "dayjs/plugin/weekday";
import "dayjs/locale/zh-cn";
import { getToken } from "@/utils/auth";

dayjs.extend(weekday);
dayjs.locale("zh-cn");

const router = useRouter();
const routerStore = useRouterStoreHook();

interface Props {
  data?: Array<any>;
  selectionData?: Array<string>;
  // 1 厂务设备    2 FAB机台
  chart?: number;
}

const props = withDefaults(defineProps<Props>(), { chart: 1 });

const emits = defineEmits(["date-change", "sort-change", "selection-change"]);

const loading = defineModel("loading", { type: Boolean, default: false });
const startDate = defineModel("startDate", { type: String, default: "" });
const endDate = defineModel("endDate", { type: String, default: "" });

const commonTableRef = ref<InstanceType<typeof commonTable> | null>(null);
const commonTableKey = ref<string>(Math.random().toString(36).slice(2, 10));
const pmPlanDetailData = ref<Record<string, any>>({});
const pmPlanDetailVisible = ref<boolean>(false);
const scrollbarHeight = inject<SizeType>(HeightKey, ref<number>(0));
// gunter  甘特图   chart  table图
const chartType = inject<ChartTypeType>(ChartTypeKey, ref<string>("gunter"));
const chartList = inject<ChartListType>(ChartListKey, ref<Array<number>>([]));

const factoryLock = inject<LockType>(FactoryLockTypeKey, ref<boolean>(false));
const workbenchLock = inject<LockType>(WorkbenchLockTypeKey, ref<boolean>(false));

const gunterTableData = computed(() => useGunterTableData(props.data));

const toPMPlayDetail = (scope: any) => {
  const {
    row: { planId = "", category = "" }
  } = scope;
  const path = "/all/equip/epm/plan/list";
  const facCode = localStorage.getItem("facCode");
  const fullpath = `/pmPlan/list?isView=true&id=${planId}&pmType=${category}&ssoToken=${getToken().accessToken}&isHiddenMenu=true&facCode=${facCode}`;
  const query = { fullpath };
  const { href } = router.resolve({ path, query });
  window.open(href, "_blank");
};

const toFabOrArchive = (scope: any) => {
  const {
    row: { deviceId: eqpId = "" }
  } = scope;
  const path = props.chart === 1 ? "/all/equip/archive/list" : "/fullScreen/fab/detail";
  let params = encodeURI(JSON.stringify({ eqpId }));
  const query = props.chart === 1 ? { eqpId } : { params };
  const { href } = router.resolve({ path, query });
  window.open(href, "_blank");
};

const pmDetailHandler = async (scope: any) => {
  const {
    row: { planNo }
  } = scope;
  const params = { planNo };
  let res: Record<string, any> = null;
  if (props.chart === 1) {
    res = await getFactoryPMDetail(params);
  } else {
    res = await getFabPMDetail(params);
  }
  if (res?.devicePm) {
    pmPlanDetailData.value = res.devicePm as Record<string, any>;
    pmPlanDetailData.value.itemDtoList = res.children;
  }
  pmPlanDetailVisible.value = true;
};

const tableCloumns = computed(() => {
  return useTableCloumns(
    props.chart,
    chartType.value,
    startDate.value,
    endDate.value,
    dateChangeHandler,
    pmDetailHandler,
    toPMPlayDetail,
    toFabOrArchive
  );
});

const tableCloumns2 = computed(() => {
  return useTableCloumns2(props.chart, toPMPlayDetail, toFabOrArchive, pmDetailHandler);
});

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "详情",
    auth: `${routerStore.subject}_FAB_MAINTENANCE_PMPLAN_DETAIL_BTN`,
    icon: markRaw(Modeling),
    click: (scope: any) => toFabOrArchive(scope)
  },
  {
    content: "查看",
    auth: `${routerStore.subject}_FAB_MAINTENANCE_PMPLAN_CHECK_BTN`,
    icon: markRaw(View),
    click: (scope: any) => pmDetailHandler(scope)
  }
];

const dateChangeHandler = ({ s, e }: any) => {
  startDate.value = s;
  endDate.value = e;
  emits("date-change", { startDate: s, endDate: e }, () => (commonTableKey.value = Math.random().toString(36).slice(2, 10)));
};

const getRowKey = row => {
  return row.planNo;
};

const spanMethod = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType) => {
  if ((props.chart === 1 && columnIndex === 7) || (props.chart === 2 && columnIndex === 6)) {
    return [1, 7];
  } else if ((props.chart === 1 && columnIndex > 7 && columnIndex < 14) || (props.chart === 2 && columnIndex > 6 && columnIndex < 13)) {
    return [0, 0];
  } else if ((props.chart === 1 && columnIndex === 14) || (props.chart === 2 && columnIndex === 13)) {
    return [1, 7];
  } else if ((props.chart === 1 && columnIndex > 14 && columnIndex < 21) || (props.chart === 2 && columnIndex > 13 && columnIndex < 20)) {
    return [0, 0];
  } else if ((props.chart === 1 && columnIndex === 21) || (props.chart === 2 && columnIndex === 20)) {
    return [1, 7];
  } else if ((props.chart === 1 && columnIndex > 21 && columnIndex < 28) || (props.chart === 2 && columnIndex > 20 && columnIndex < 27)) {
    return [0, 0];
  } else if ((props.chart === 1 && columnIndex === 28) || (props.chart === 2 && columnIndex === 27)) {
    return [1, 7];
  } else if ((props.chart === 1 && columnIndex > 28 && columnIndex < 35) || (props.chart === 2 && columnIndex > 27 && columnIndex < 34)) {
    return [0, 0];
  }
};

const headerCellStyleFn = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
  const style = {};
  style["padding"] = 0;
  if ((props.chart === 1 && columnIndex === 6) || (props.chart === 2 && columnIndex === 5)) {
    style["text-align"] = "center";
  }
  return style;
};

const cellStyleFn = ({ row, column, rowIndex, columnIndex }) => {
  const style = {};
  if (
    (props.chart === 1 && (columnIndex === 7 || columnIndex === 14 || columnIndex === 21 || columnIndex === 28)) ||
    (props.chart === 2 && (columnIndex === 6 || columnIndex === 13 || columnIndex === 20 || columnIndex === 27))
  ) {
    style["padding"] = "0px";
  }
  return style;
};

const headerCellStyleFn2 = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
  const style = {};
  if ((props.chart === 1 && columnIndex === 10) || (props.chart === 2 && columnIndex === 7)) {
    style["text-align"] = "center";
  }
  return style;
};

const cellStyleFn2 = ({ row, column, rowIndex, columnIndex }) => {
  const { earlyDate, dueDate, lateDate } = row;
  let backgroundColor = "transparent";
  const color = "#fff";
  // 黄 #FFFF76FF
  // 橙 #F59E0BFF
  // 红 #FF2B2BFF
  if ((props.chart === 1 && columnIndex === 10) || (props.chart === 2 && columnIndex === 7)) {
    if (dayjs().valueOf() >= dayjs(earlyDate).valueOf() && dayjs().valueOf() <= dayjs(dueDate).valueOf()) {
      backgroundColor = "#FFFF76FF";
      return { color: "#333", backgroundColor };
    }
  } else if ((props.chart === 1 && columnIndex === 11) || (props.chart === 2 && columnIndex === 8)) {
    if (dayjs().valueOf() >= dayjs(earlyDate).valueOf() && dayjs().valueOf() <= dayjs(dueDate).valueOf()) {
      backgroundColor = "#FFFF76FF";
      return { color: "#333", backgroundColor };
    }
    if (dayjs().valueOf() >= dayjs(dueDate).valueOf() && dayjs().valueOf() <= dayjs(lateDate).valueOf()) {
      backgroundColor = "#F59E0BFF";
      return { color: "#333", backgroundColor };
    }
  } else if ((props.chart === 1 && columnIndex === 12) || (props.chart === 2 && columnIndex === 9)) {
    if (dayjs().valueOf() > dayjs(lateDate).valueOf()) {
      backgroundColor = "#FF2B2BFF";
      return { color, backgroundColor };
      // backgroundColor = "#F59E0BFF";
      // return { color: "#333", backgroundColor };
    }
  } else {
    return {};
  }
};

const sortChangeHandler = ({ column, order }: CommonTable.SortParams) => {
  const { property: sortColumn = "" } = column;
  // order  -  ascending  descending
  // chart   1 厂务设备    2 FAB机台
  let params = null;
  const columnName = sortColumn;
  const asc = order === "ascending" ? true : order === "descending" ? false : "";
  const orderList = [{ columnName, asc }];
  params = order ? { orderList } : null;
  emits("sort-change", params);
};

const toggleSelection = () => {
  if (!props.selectionData.length) return;
  props.data.forEach((row: any) => {
    const { deviceId: id = "" } = row;
    commonTableRef.value.el?.toggleRowSelection(row, props.selectionData.includes(id));
  });
};

const clearSelection = () => {
  commonTableRef.value.el?.clearSelection();
};

const clearSort = () => {
  commonTableRef.value.el?.clearSort();
};

const getSelectableFn = (row: any, index: number): boolean => {
  if (chartList.value.length > 1) {
    if (!factoryLock.value && !workbenchLock.value) {
      return true;
    } else {
      if (props.chart === 1) {
        return factoryLock.value;
      } else {
        return workbenchLock.value;
      }
    }
  } else {
    return true;
  }
};

defineExpose({ el: commonTableRef.value, toggleSelection, clearSelection, clearSort });
</script>

<template>
  <div class="pm-table">
    <commonTable
      v-if="chartType === 'gunter'"
      ref="commonTableRef"
      class="common-table-gunter"
      :key="commonTableKey"
      v-model:loading="loading"
      selection
      :pagination="false"
      :height="scrollbarHeight"
      :tableCloumns="tableCloumns"
      :list="gunterTableData"
      :selectable="getSelectableFn"
      :row-key="getRowKey"
      :span-method="spanMethod"
      :header-cell-style="headerCellStyleFn"
      :cell-style="cellStyleFn"
      @selection-change="val => emits('selection-change', val)"
    />
    <commonTable
      v-if="chartType === 'chart'"
      ref="commonTableRef"
      class="common-table-chart"
      indexNeed
      v-model:loading="loading"
      selection
      :pagination="false"
      :height="scrollbarHeight"
      :tableCloumns="tableCloumns2"
      :list="data"
      :selectable="getSelectableFn"
      :row-key="getRowKey"
      :header-cell-style="headerCellStyleFn2"
      :cell-style="cellStyleFn2"
      :operationOptions="operationOptions"
      @sort-change="sortChangeHandler"
      @selection-change="val => emits('selection-change', val)"
    />
    <pmPlanDetail v-if="pmPlanDetailVisible" v-model="pmPlanDetailVisible" :data="pmPlanDetailData" :chart="chart" />
  </div>
</template>

<style lang="scss" scoped>
:deep(.px-table) {
  .pm-gunter {
    vertical-align: bottom;
    .cell {
      height: var(--px-table__cell-height);
      line-height: var(--px-table__cell-height);
      padding: 0;
      overflow: visible;
      text-align: center;
    }
  }
}
</style>
